package com.grace.common;

import com.grace.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    //声明一个时间
    private static final String START_TIME = "requestStartTime";

    //请求接口之前的处理方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Map paramMap = request.getParameterMap();
        log.info("request start, url:{},params:{}", url, JsonMapper.obj2String(paramMap));
        long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        return super.preHandle(request, response, handler);
    }

    //请求接口成功之后的处理方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url = request.getRequestURL().toString();
        long start = (Long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        log.info("request finished, url:{},cost:{}", url, end - start);
        super.postHandle(request, response, handler, modelAndView);
        //调用removeThreadLocalInfo
        removeThreadLocalInfo();
    }

    //请求接口之后的处理方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        long start = (Long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        log.info("request completed, url:{},cost:{}", url, end - start);
        super.afterCompletion(request, response, handler, ex);
        //调用removeThreadLocalInfo
        removeThreadLocalInfo();
    }

    public void removeThreadLocalInfo() {
        RequestHolder.remove();
    }
}
